//
//  AssetMenuView.m
//  AppleMarket
//
//  Created by yangy on 01/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "AssetMenuView.h"

@implementation AssetMenuItem
+ (instancetype) menuItemTitle:(NSString*) title image:(UIImage*) image action:(void((^)(void))) actionHandler;
{
    AssetMenuItem *item = [[[self class] alloc] init];
    item.title = title;
    item.image = image;
    item.clickHandler = actionHandler;
    return item;
}
@end


@interface AssetMenuView()
@property (nonatomic, strong) NSMutableArray<UIButton*> *itemButtons;
@end

@implementation AssetMenuView

+ (AssetMenuView*) menuViewItems:(NSArray<AssetMenuItem*>*) items frame:(CGRect) frame
{
    AssetMenuView *menuView = [[[self class] alloc] initWithFrame:frame items:items];
    return menuView;
}

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray<AssetMenuItem*>*) items
{
    self = [super initWithFrame:frame];
    if(self){
        __block UIButton *lastButton = nil;
        [items enumerateObjectsUsingBlock:^(AssetMenuItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            itemBtn.titleLabel.font = kFont(14);
            [itemBtn setTitle:obj.title forState:UIControlStateNormal];
            [itemBtn setImage:obj.image forState:UIControlStateNormal];
            [itemBtn setImagePosition:Top spacing:13];
            [itemBtn setTitleColor:kColorWithHex(0x4A647A) forState:UIControlStateNormal];
            [[itemBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if(obj.clickHandler){
                    obj.clickHandler();
                }
            }];;
            [self.itemButtons addObject:itemBtn];
            [self addSubview:itemBtn];
            
            CGFloat hSpace = (self.width - 30 - items.count) / (items.count);
            // 限制交易对象识别安全系数
            [itemBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(self);
                if(!lastButton){
                    make.left.mas_equalTo(self).offset(15);
                }else{
                    make.left.mas_equalTo(lastButton.mas_right);
                }
                make.width.mas_equalTo(hSpace);
                lastButton = itemBtn;
            }];
        }];
    }
    return self;
}

- (NSMutableArray<UIButton *> *)itemButtons
{
    if(!_itemButtons){
        _itemButtons = [[NSMutableArray alloc] init];
    }
    return _itemButtons;
}

@end
